package com.yifeng.repo.micro.service.server.engine.log.sqllog;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author zyh
 */
@Slf4j
public class SqlLogServlet extends HttpServlet {
    private static final String PRINT_ENABLE = "printEnable";
    private static final String PRINT_DISABLE = "printDisable";
    private static final String PRINT_2_LOG_TYPE = "printLog";
    private static final String PRINT_2_RESP_TYPE = "printResp";
    private static final String PRINT_2_FILE_TYPE = "printFile";
    private static final String CLEAR_SQL_TYPE = "clear";
    private static final String SQL_FILE_KEY_WORD = "yfcloud_sql";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String type = req.getParameter("param");
        switch (type) {
            case PRINT_ENABLE:
                this.enable(resp);
                break;
            case PRINT_DISABLE:
                this.disable(resp);
                break;
            case PRINT_2_LOG_TYPE:
                this.print2Log(resp);
                break;
            case PRINT_2_RESP_TYPE:
                this.print2Resp(resp);
                break;
            case PRINT_2_FILE_TYPE:
                this.print2File(resp);
                break;
            case CLEAR_SQL_TYPE:
                this.clearSql(resp);
                break;
            default:
                throw new RuntimeException("非法参数");
        }
    }

    private void enable(HttpServletResponse response) {
        SqlLogInterceptor.enable();
        write2Json(response, "sql print enable success");
    }

    private void disable(HttpServletResponse response) {
        SqlLogInterceptor.disable();
        SqlLogInterceptor.clear();
        write2Json(response, "sql print disable success");
    }

    private void check(HttpServletResponse response) {
        if (!SqlLogInterceptor.isEnabled()) {
            write2Json(response, "please enable sql print");
        }
    }

    private void print2Log(HttpServletResponse response) {
        check(response);
        List<String> sqlList = SqlLogInterceptor.getSqlList();
        if (sqlList.isEmpty()) {
            log.info("sqlList is empty, stop print sql");
            return;
        }
        log.info("****" + SQL_FILE_KEY_WORD + "print start" + "****");
        int count = 1;
        for (String sql : sqlList) {
            log.info(SQL_FILE_KEY_WORD + "-" + (count++) + ": " + sql);
        }
        log.info("****" + SQL_FILE_KEY_WORD + "print end" + "****");
        write2Json(response, "print sql log success");
    }

    private void print2Resp(HttpServletResponse response) {
        check(response);
        this.write2Json(response, SqlLogInterceptor.getSqlList());
    }

    private void print2File(HttpServletResponse response) {
        check(response);
        List<String> sqlList = SqlLogInterceptor.getSqlList();
        StringBuilder stringBuilder = new StringBuilder();
        int count = 1;
        for (String s : sqlList) {
            stringBuilder.append(count++).append("- ")
                    .append(s).append(",").append("\r\n");
        }
        this.write2File(response, stringBuilder.toString(),"sql-log.sql");
    }

    private void clearSql(HttpServletResponse response) {
        SqlLogInterceptor.clear();
        write2Json(response, "clear sql success");
    }

    private void write2Json(HttpServletResponse response, Object content) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");
            writer.write(new ObjectMapper().writer().writeValueAsString(content));
            writer.flush();
        } catch (IOException e) {
            log.error("SQL打印异常,error={}", e.getMessage());
        }
    }

    private void write2File(HttpServletResponse response, String content, String filename) {
        try (PrintWriter writer = response.getWriter()) {
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            log.error("SQL打印异常,error={}", e.getMessage());
        }
    }

}
